package com.waikuai.shop.service.impl;

import com.waikuai.shop.entity.Permission;
import com.waikuai.shop.entity.Role;
import com.waikuai.shop.entity.User;
import com.waikuai.shop.mapper.PermissionMapper;
import com.waikuai.shop.mapper.RoleMapper;
import com.waikuai.shop.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户详情服务实现类
 * @author waikuai
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    private final PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        // 查找用户
        User user = userMapper.findByAccount(account);
        if (user == null) {
            log.debug("用户不存在: {}", account);
            throw new UsernameNotFoundException("用户不存在: " + account);
        }

        // 检查用户状态
        if (user.getStatus() == 0) {
            log.debug("用户已被禁用: {}", account);
            throw new UsernameNotFoundException("用户已被禁用: " + account);
        }

        // 获取用户角色
        Collection<? extends GrantedAuthority> authorities = getAuthorities(user.getId());

        log.debug("用户详情加载成功: {}, 角色数量: {}", account, authorities.size());
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                user.getStatus() == 1,
                true,
                true,
                true,
                authorities
        );
    }

    /**
     * 获取用户权限
     * @param userId 用户ID
     * @return 权限集合
     */
    private Collection<? extends GrantedAuthority> getAuthorities(Long userId) {
        // 获取用户角色
        List<Role> roles = roleMapper.findByUserId(userId);
        List<GrantedAuthority> authorities = roles.stream()
                .map(role -> new SimpleGrantedAuthority(role.getRoleCode()))
                .collect(Collectors.toList());

        // 获取用户权限
        List<Permission> permissions = permissionMapper.findByUserId(userId);
        List<GrantedAuthority> permissionAuthorities = permissions.stream()
                .map(permission -> new SimpleGrantedAuthority(permission.getPermissionCode()))
                .collect(Collectors.toList());

        authorities.addAll(permissionAuthorities);

        return authorities;
    }
}